package utils.commons;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * <p>
 * Title: 转换工具类函数
 * </p>
 * <p>
 * Description:WEB工程中亦有此类
 * </p>
 * <p>
 * Copyright: Copyright (c) 2011
 * </p>
 * <p>
 * Company: nova
 * </p>
 * 
 * @author lanckun
 * @version 0.1
 */
//字符串转为字节类型图片的转换主要实现方法
public class ConversionUtil {
	private static Logger log = LoggerFactory.getLogger(ConversionUtil.class);

	public static byte[] toByteArr(String s) {
		if (s==null)//|| "".equals("")
		{
			return null;
		}
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(
						s.substring(i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				log.error("字符串" + s + "类型转换失败", e);
			}
		}
		return baKeyword;
	}
//图片的转换主要实现方法
	public static String toHexString(byte[] bytes) {
		String hexString = "0123456789ABCDEF";
		// 根据默认编码获取字节数组
		// byte[] bytes = str.getBytes();
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		// 将字节数组中每个字节拆解成2位16进制整数
		for (int i = 0; i < bytes.length; i++) {
			sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
		}
		return sb.toString();
	}

	public static byte[] objectToByte(Object obj) {
		byte[] bytes = null;
		try {
			ByteArrayOutputStream bo = new ByteArrayOutputStream();
			ObjectOutputStream oo = new ObjectOutputStream(bo);
			oo.writeObject(obj);
			bytes = bo.toByteArray();
			bo.close();
			oo.close();
		} catch (Exception e) {
			log.error("字节输出错误", e);
		}
		return (bytes);
	}

	public static Object byteToObject(byte[] bytes) {
		Object obj = null;
		try {
			// bytearray to object
			ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
			ObjectInputStream oi = new ObjectInputStream(bi);

			obj = oi.readObject();

			bi.close();
			oi.close();
		} catch (Exception e) {
			log.error("字节转换对象错误", e);
		}
		return obj;
	}

	public static String objectToString(Object obj) {
		return toHexString(objectToByte(obj));
	}
}
